package com.pz.cloud.framework.base.model;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.pz.cloud.framework.base.constants.CodeContants;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import lombok.Data;
import lombok.SneakyThrows;

/**
 * 返回结果model
 * @author 3hmzz
 */
@Data
public class BaseResult {
	protected Integer code;
	protected String msg;
    protected Object data;

	public BaseResult() {
		code = CodeContants.SUCCESS;
		msg = "成功";
	}

	public BaseResult(Object data) {
		code = CodeContants.SUCCESS;
		msg = "成功";
		this.data = data;
	}

	public BaseResult(Integer code , String msg) {
		this.code = code;
		this.msg = msg;
	}

    public BaseResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

	@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
	public Boolean isSuccess(){
		return this.code==0||this.code==CodeContants.SUCCESS;
	}
    @SneakyThrows
	@Override
    public String toString(){
//		ObjectMapper om = new ObjectMapper();
//		String s = om.writeValueAsString(this);
		JSONObject json = new JSONObject();
        json.put("code",code);
        json.put("msg",msg);
        json.put("data",data);
	    return json.toString();
    }

    public static BaseResult ok(){
    	return new BaseResult();
	}
    public static BaseResult ok(Object data){
    	return new BaseResult(data);
	}

    public static BaseResult error(String msg){
    	return new BaseResult(CodeContants.IINTERNAL_ERROR,msg);
	}
    public static BaseResult error(CustomRuntimeException e){
    	return new BaseResult(e.getCode(),e.getMessage(),e.getResult());
	}
}
